package com.ruoyi.system.api.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.JPushConfig;
import com.ruoyi.common.config.PushConfig;
import com.ruoyi.common.jpush.JPushClientUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OkHttpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.*;
import com.ruoyi.system.api.service.CcService;
import com.ruoyi.system.api.service.IInterfaceOperationLogService;
import com.ruoyi.system.api.service.IServiceInstrumentService;
import okhttp3.FormBody;
import okhttp3.Response;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.service.IServiceNoticeService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * 服务派单主 (数据来源于CC端主动调用)Service业务层处理
 *
 * @author shihx
 * @date 2020-03-02
 */
@Service
public class ServiceNoticeServiceImpl implements IServiceNoticeService {

    private static final Logger log = LoggerFactory.getLogger(ServiceNoticeServiceImpl.class);

    @Autowired
    private ServiceNoticeMapper serviceNoticeMapper;

    @Autowired
    private CcService ccService;

    @Autowired
    private BatchLogMapper batchLogMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 配置文件
     */
    @Autowired
    private Global global;

    /**
     * 接口调用日志
     */
    @Autowired
    private IInterfaceOperationLogService iInterfaceOperationLogService;

    /**
     * 服务单TL转派记录表 数据由我方生成并提交给CC端
     */
    @Autowired
    private TransferRecordMapper transferRecordMapper;

    /**
     * 服务单派单子表
     */
    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    @Autowired
    private ServiceDetailsMapper serviceDetailsMapper;

    @Autowired
    private JPushConfig jPushConfig;

    @Autowired
    private JpushLogMapper jpushLogMapper;


    @Autowired
    private ServiceInstrumentMapper serviceInstrumentMapper;

    @Autowired
    private InstrumentInfoMapper instrumentInfoMapper;

    @Autowired
    private ReportInfoMapper reportInfoMapper;

    @Autowired
    private ServiceLogMapper serviceLogMapper;

    @Autowired
    private StServiceReportMapper stServiceReportMapper;

    @Autowired
    private StInfoUpdateMapper stInfoUpdateMapper;


    /**
     * 查询服务派单主 (数据来源于CC端主动调用)
     *
     * @param id 服务派单主 (数据来源于CC端主动调用)ID
     * @return 服务派单主 (数据来源于CC端主动调用)
     */
    @Override
    public ServiceNotice selectServiceNoticeById(Long id) {
        return serviceNoticeMapper.selectServiceNoticeById(id);
    }

    /**
     * 查询服务派单主 (数据来源于CC端主动调用)列表
     *
     * @param serviceNotice 服务派单主 (数据来源于CC端主动调用)
     * @return 服务派单主 (数据来源于CC端主动调用)
     */
    @Override
    public List<ServiceNotice> selectServiceNoticeList(ServiceNotice serviceNotice) {
        return serviceNoticeMapper.selectServiceNoticeList(serviceNotice);
    }

    /**
     * 新增服务派单主 (数据来源于CC端主动调用)
     *
     * @param serviceNotice 服务派单主 (数据来源于CC端主动调用)
     * @return 结果
     */
    @Override
    public int insertServiceNotice(ServiceNotice serviceNotice) {
        serviceNotice.setCreateTime(DateUtils.getNowDate());
        return serviceNoticeMapper.insertServiceNotice(serviceNotice);
    }

    /**
     * 修改服务派单主 (数据来源于CC端主动调用)
     *
     * @param serviceNotice 服务派单主 (数据来源于CC端主动调用)
     * @return 结果
     */
    @Override
    public int updateServiceNotice(ServiceNotice serviceNotice) {
        return serviceNoticeMapper.updateServiceNotice(serviceNotice);
    }

    /**
     * 删除服务派单主 (数据来源于CC端主动调用)对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteServiceNoticeByIds(String ids) {
        return serviceNoticeMapper.deleteServiceNoticeByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除服务派单主 (数据来源于CC端主动调用)信息
     *
     * @param id 服务派单主 (数据来源于CC端主动调用)ID
     * @return 结果
     */
    @Override
    public int deleteServiceNoticeById(Long id) {
        return serviceNoticeMapper.deleteServiceNoticeById(id);
    }

    @Override
    public ResponseWithData<?> getMyPlanCount(String EnginnerId, String customerName, String serviceType) throws Exception {
        MyPlanCount myPlanCount = null;
        myPlanCount = serviceNoticeMapper.getMyPlanCount(EnginnerId, customerName, serviceType);
        return new ResponseWithData<>().success(myPlanCount).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> getMyTeamPlanCount(String EnginnerId, String customerName, String serviceType, String enginnerName) throws Exception {
        Map<String, Integer> map = new HashMap();
        map.put("daizhipai", 0);
        map.put("daijieshou", 0);
        map.put("jinxingzhong", 0);
        //待指派
        ServiceNotice serviceNotice = new ServiceNotice();
        serviceNotice.setTeamleaderId(EnginnerId);
        serviceNotice.setProvince("1");
        serviceNotice.setCustomerName(customerName);
        serviceNotice.setServiceType(serviceType);
        serviceNotice.setServiceStatus(enginnerName);
        int ll = serviceNoticeMapper.getTeamServiceNoticesCount(serviceNotice);
        if (!ObjectUtils.isEmpty(ll)) {
            map.put("daizhipai", ll);
        }

        //待接收
        ll = serviceNoticeMapper.getMyServiceNoticeCount(EnginnerId, "'0'", null, null);
        if (!ObjectUtils.isEmpty(ll)) {
            map.put("daijieshou", ll);
        }
        // 进行中
        ll = serviceNoticeMapper.getMyServiceNoticeCount(EnginnerId, "'1','2','3','4','5'", customerName, serviceType);
        if (!ObjectUtils.isEmpty(ll)) {
            map.put("jinxingzhong", ll);
        }

        return new ResponseWithData<>().success(map).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> getMyServiceNotice(String EnginnerId, String state, String customerName, String serviceType) throws Exception {
        List<ServiceNotice> list = null;
        // 待接受
        if ("0".equals(state)) {
            list = serviceNoticeMapper.getMyServiceNotice(EnginnerId, "'0'", null, null);
        }
        // 进行中
        if ("1".equals(state)) {
            list = serviceNoticeMapper.getMyServiceNotice(EnginnerId, "'1','2','3','4','5'", customerName, serviceType);
        }
        for (ServiceNotice serviceNotice1 : list) {
            if (StringUtils.equals("1", serviceNotice1.getUserIsdpel())) {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getIsVip());

                } else {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getEnginnerType());
                }
            } else {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType(serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType(serviceNotice1.getEnginnerType());
                }

            }
            StInfoUpdate stInfoUpdate = new StInfoUpdate();
            stInfoUpdate.setServiceNo(serviceNotice1.getServiceNo());
            stInfoUpdate.setDelFlag("0");
            stInfoUpdate.setType("1");
            //stInfoUpdate.setStatus(0L);
            List<StInfoUpdate> stInfoUpdateList = stInfoUpdateMapper.selectStInfoUpdateList(stInfoUpdate);
            //1 表示不一致，0 表示一致
            if (stInfoUpdateList.size() > 0) {
                serviceNotice1.setSnflag("1");
            } else {
                serviceNotice1.setSnflag("0");
            }

        }
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> getMyServiceNoticeDetail(String ServiceNoticeId, String EnginnerId) throws Exception {
        ServiceInstrument serviceInstrument = new ServiceInstrument();
        serviceInstrument.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
        List<ServiceInstrument> instrumentList = serviceInstrumentMapper.selectServiceInstrumentList(serviceInstrument);
        Map<String, List> map = new HashMap();
        List<ServiceNotice> list = serviceNoticeMapper.getMyServiceNoticeDetail(ServiceNoticeId, EnginnerId);
        ServiceNotice serviceNotice = null;
        if (!ObjectUtils.isEmpty(list)) {
            serviceNotice = list.get(0);
            serviceNotice.setDivBu(instrumentList.get(0).getDiviBu());
        }
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> getTeamleaderList(String TeamleaderId, String TeamleaderName) throws Exception {

        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("getTLList.asmx/getTL");
//        url.append("&Teamleader_id=").append(TeamleaderId);
//        url.append("&Teamleader_name=").append(TeamleaderName);

        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("Teamleader_id", TeamleaderId);
        if (null == TeamleaderName) {
            TeamleaderName = "";
        }
        builder.add("Name", TeamleaderName);

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.3获取TL列表接口");
        interfaceOperationLog.setInterfaceType("getTeamleaderList");
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setFseId(TeamleaderId);
//        interfaceOperationLog.setInterfaceRequest(login.toString());
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口发生异常").code(202);
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    /** 获取CC端返回的信息 */
                    JSONArray jsonStr = obj.getJSONArray("record");

                    return new ResponseWithData().success(jsonStr).msg("查询成功").code(200);
                }
            }
        }
        return new ResponseWithData().success().msg("查询失败 调用CC端获取TL名下工程师接口返回异常").code(201);
    }

    @Override
    public ResponseWithData<?> TransferTL(String TeamleaderId, String serviceNo, String NewTeamleaderId) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 提交时间
        Date submittlTime = new Date();

        // 保存进本地数据库
        TransferRecord transferRecord = new TransferRecord();
        transferRecord.setTeamleaderId(Long.parseLong(TeamleaderId));
        transferRecord.setServiceNo(serviceNo);
        transferRecord.setNewTeamleaderId(Long.parseLong(NewTeamleaderId));
        transferRecord.setSubmittlTime(submittlTime);
        transferRecord.setCreateTime(new Date());
        transferRecordMapper.insertTransferRecord(transferRecord);

        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("sendUpdateTL.asmx/sendUpdateTLHandle");

        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("Teamleader_id", TeamleaderId);
        builder.add("service_no", serviceNo);
        builder.add("submittl_time", submittlTime.getTime() + "");
        builder.add("New_teamleader_id", NewTeamleaderId);

        StringBuffer buffer = new StringBuffer();
        buffer.append("Teamleader_id:" + TeamleaderId + ";");
        buffer.append("service_no:" + serviceNo + ";");
        buffer.append("submittl_time:" + submittlTime.getTime() + ";");
        buffer.append("New_teamleader_id:" + NewTeamleaderId);

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.4TL转派其他TL接口");
        interfaceOperationLog.setInterfaceType("TransferTL");
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setFseId(TeamleaderId);
        interfaceOperationLog.setServiceNo(serviceNo);
        interfaceOperationLog.setInterfaceRequest(buffer.toString());
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            return new ResponseWithData().success().msg("转派失败 调用CC端转派其他TL接口发生异常").code(202);
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    /** 获取CC端返回的信息 */
                    JSONObject jsonStr = obj.getJSONObject("record");

                    /** 返回成功后更新记录表 */
                    transferRecord.setSyncFlag("1");
                    transferRecord.setSyncTime(new Date());
                    transferRecord.setUpdateTime(new Date());
                    transferRecordMapper.updateTransferRecord(transferRecord);

                    /** 修改服务单TL为新的TL */
                    ServiceNotice serviceNotice = new ServiceNotice();
                    serviceNotice.setTeamleaderId(NewTeamleaderId);
                    serviceNotice.setServiceNo(serviceNo);
                    serviceNoticeMapper.updateServiceNoticeByServiceNo(serviceNotice);

                    /** 调用推送给转派的TL推送消息 */
                    // 获取转派TL的姓名
                    User user = new User();
                    user.setEnginnerId(Long.parseLong(TeamleaderId));
                    List<User> users = userMapper.selectUserList(user);
                    String content = "";
                    if (users != null && users.size() > 0) {
                        content = PushConfig.TRANSFER_TL_CONTENT.replaceAll("NAME", users.get(0).getName()).replaceAll("NO", serviceNo);
                    }

                    User user1 = new User();
                    user1.setEnginnerId(Long.parseLong(NewTeamleaderId));
                    List<User> users1 = userMapper.selectUserList(user1);
                    if (users1 != null && users1.size() > 0 && StringUtils.isNotEmpty(users1.get(0).getRegistrationId())) {
                        // 推送额外参数
                        JsonObject extra = new JsonObject();
                        extra.addProperty("type", PushConfig.TRANSFER_TL_STATE);
                        extra.addProperty("serviceNo", serviceNo);
                        extra.addProperty("teamleaderId", NewTeamleaderId);

                        JpushLog jpushLog = new JpushLog();
                        PushResult pushResult = null;
                        try {
                            JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                            pushResult = JPushClientUtil.getInstance().sendPush(users1.get(0).getRegistrationId(), PushConfig.TRANSFER_TL_TITLE, content, extra);

                            jpushLog.setStatuscode(pushResult.statusCode + "");
                            jpushLog.setMsgId(pushResult.msg_id + "");
                            jpushLog.setSendno(pushResult.sendno + "");
                        } catch (APIConnectionException e) {
                            // e.printStackTrace();
                            // Connection error, should retry later
                            log.error("Connection error, should retry later", e);
                        } catch (APIRequestException e) {
                            // e.printStackTrace();
                            // Should review the error, and fix the request
                            log.error("Should review the error, and fix the request", e);
                            log.info("HTTP Status: " + e.getStatus());
                            log.info("Error Code: " + e.getErrorCode());
                            log.info("Error Message: " + e.getErrorMessage());
                            jpushLog.setStatuscode(e.getErrorCode() + "");
                            jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                        }
                        // 保存推送日志
                        jpushLog.setEnginnerId(NewTeamleaderId);
                        jpushLog.setType(PushConfig.ONE_PUSH);
                        jpushLog.setRegistrationId(users1.get(0).getRegistrationId());
                        jpushLog.setState(PushConfig.TRANSFER_TL_STATE);
//                    jpushLog.setNoticeId(serviceNotice.getId());
                        jpushLog.setServiceNo(serviceNo);
                        jpushLog.setTitle(PushConfig.TRANSFER_TL_TITLE);
                        jpushLog.setContent(content);
                        jpushLog.setExtra(extra.toString());
                        jpushLog.setPushTime(new Date());
                        jpushLog.setCreateTime(new Date());
                        jpushLogMapper.insertJpushLog(jpushLog);
                    }

                    return new ResponseWithData().success(jsonStr).msg("转派成功").code(200);
                } else {
                    return new ResponseWithData().success().msg("转派失败").code(202);
                }
            }
        }
        return new ResponseWithData().success().msg("转派失败 调用CC端转派其他TL接口返回异常").code(201);
    }


    @Override
    public ResponseWithData<?> TransferTL2(String TeamleaderId, String serviceNo, String NewTeamleaderId) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 提交时间
        Date submittlTime = new Date();

        // 保存进本地数据库
        TransferRecord transferRecord = new TransferRecord();
        transferRecord.setTeamleaderId(Long.parseLong(TeamleaderId));
        transferRecord.setServiceNo(serviceNo);
        transferRecord.setNewTeamleaderId(Long.parseLong(NewTeamleaderId));
        transferRecord.setSubmittlTime(submittlTime);
        transferRecord.setCreateTime(new Date());
        transferRecordMapper.insertTransferRecord(transferRecord);

        String ccServerUrl = global.getCcServerUrl();
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("sendUpdateTL.asmx/sendUpdateTLHandle");

        /** POST请求 参数赋值 */
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("Teamleader_id", TeamleaderId);
        builder.add("service_no", serviceNo);
        builder.add("submittl_time", submittlTime.getTime() + "");
        builder.add("New_teamleader_id", NewTeamleaderId);

        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.4TL转派其他TL接口");
        interfaceOperationLog.setInterfaceType("TransferTL");
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setFseId(TeamleaderId);
        interfaceOperationLog.setServiceNo(serviceNo);
//        interfaceOperationLog.setInterfaceRequest(login.toString());
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            return new ResponseWithData().success().msg("转派失败 调用CC端转派其他TL接口发生异常").code(202);
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {

                    /** 获取CC端返回的信息 */
                    JSONObject jsonStr = obj.getJSONObject("record");

                    /** 返回成功后更新记录表 */
                    transferRecord.setSyncFlag("1");
                    transferRecord.setSyncTime(new Date());
                    transferRecord.setUpdateTime(new Date());
                    transferRecordMapper.updateTransferRecord(transferRecord);

                    /** 修改服务单TL为新的TL */
                    ServiceNotice serviceNotice = new ServiceNotice();
                    serviceNotice.setTeamleaderId(NewTeamleaderId);
                    serviceNotice.setServiceNo(serviceNo);
                    serviceNoticeMapper.updateServiceNoticeByServiceNo(serviceNotice);

                    /** 调用推送给转派的TL推送消息 */
                    // 获取转派TL的姓名
//                    User user = new User();
//                    user.setEnginnerId(Long.parseLong(TeamleaderId));
//                    List<User> users = userMapper.selectUserList(user);
//                    String content = "";
//                    if (users != null && users.size() > 0) {
//                        content = PushConfig.TRANSFER_TL_CONTENT.replaceAll("NAME", users.get(0).getName()).replaceAll("NO",serviceNo);
//                    }

//                    User user1 = new User();
//                    user1.setEnginnerId(Long.parseLong(NewTeamleaderId));
//                    List<User> users1 = userMapper.selectUserList(user1);
//                    if (users1 != null && users1.size() > 0 && StringUtils.isNotEmpty(users1.get(0).getRegistrationId())) {
//                        // 推送额外参数
//                        JsonObject extra = new JsonObject();
//                        extra.addProperty("type", PushConfig.TRANSFER_TL_STATE);
//                        extra.addProperty("serviceNo", serviceNo);
//                        extra.addProperty("teamleaderId", NewTeamleaderId);
//
//                        JpushLog jpushLog = new JpushLog();
//                        PushResult pushResult = null;
//                        try {
//                            JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
//                            pushResult = JPushClientUtil.getInstance().sendPush(users1.get(0).getRegistrationId(), PushConfig.TRANSFER_TL_TITLE, content, extra);
//
//                            jpushLog.setStatuscode(pushResult.statusCode + "");
//                            jpushLog.setMsgId(pushResult.msg_id + "");
//                            jpushLog.setSendno(pushResult.sendno + "");
//                        } catch (APIConnectionException e) {
//                            // e.printStackTrace();
//                            // Connection error, should retry later
//                            log.error("Connection error, should retry later", e);
//                        } catch (APIRequestException e) {
//                            // e.printStackTrace();
//                            // Should review the error, and fix the request
//                            log.error("Should review the error, and fix the request", e);
//                            log.info("HTTP Status: " + e.getStatus());
//                            log.info("Error Code: " + e.getErrorCode());
//                            log.info("Error Message: " + e.getErrorMessage());
//                            jpushLog.setStatuscode(e.getErrorCode() + "");
//                            jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
//                        }
//                        // 保存推送日志
//                        jpushLog.setEnginnerId(NewTeamleaderId);
//                        jpushLog.setType(PushConfig.ONE_PUSH);
//                        jpushLog.setRegistrationId(users1.get(0).getRegistrationId());
//                        jpushLog.setState(PushConfig.TRANSFER_TL_STATE);
////                    jpushLog.setNoticeId(serviceNotice.getId());
//                        jpushLog.setServiceNo(serviceNo);
//                        jpushLog.setTitle(PushConfig.TRANSFER_TL_TITLE);
//                        jpushLog.setContent(content);
//                        jpushLog.setExtra(extra.toString());
//                        jpushLog.setPushTime(new Date());
//                        jpushLog.setCreateTime(new Date());
//                        jpushLogMapper.insertJpushLog(jpushLog);
//                    }

                    return new ResponseWithData().success(jsonStr).msg("转派成功").code(200);
                } else {
                    return new ResponseWithData().success().msg("转派失败").code(202);
                }
            }
        }
        return new ResponseWithData().success().msg("转派失败 调用CC端转派其他TL接口返回异常").code(201);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWithData<?> ConfirmationDispatch(String ServiceNoticeId, String serviceNo, String EnginnerIds, String EnginnerNames, String assignId) throws Exception {
        String[] eIds = EnginnerIds.split(",");
        String[] eNames = EnginnerNames.split(",");

        for (int i = 0; i < eIds.length; i++) {

            List<User> userByServiceNoticeId = userMapper.getUserByServiceNoticeId(ServiceNoticeId);
            String content = "";
            if (userByServiceNoticeId != null && userByServiceNoticeId.size() > 0) {
                content = PushConfig.ACCEPT_CONTENT.replaceAll("NAME", userByServiceNoticeId.get(0).getName()).replaceAll("NO", serviceNo);
            }

            /** 调用推送给每个FSE推送消息 */
            User user1 = new User();
            user1.setEnginnerId(Long.parseLong(eIds[i]));
            List<User> users1 = userMapper.selectUserList(user1);
            if (users1 != null && users1.size() > 0 && StringUtils.isNotEmpty(users1.get(0).getRegistrationId())) {
                // 推送额外参数
                JsonObject extra = new JsonObject();
                extra.addProperty("type", PushConfig.ACCEPT_STATE);
                extra.addProperty("serviceNoticeId", ServiceNoticeId);
                extra.addProperty("serviceNo", serviceNo);
                extra.addProperty("teamleaderId", eIds[i]);

                JpushLog jpushLog = new JpushLog();
                PushResult pushResult = null;
                try {
                    JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                    pushResult = JPushClientUtil.getInstance().sendPush(users1.get(0).getRegistrationId(), PushConfig.ACCEPT_TITLE, content, extra);

                    jpushLog.setStatuscode(pushResult.statusCode + "");
                    jpushLog.setMsgId(pushResult.msg_id + "");
                    jpushLog.setSendno(pushResult.sendno + "");
                } catch (APIConnectionException e) {
                    // Connection error, should retry later
                    log.error("Connection error, should retry later", e);
                } catch (APIRequestException e) {
                    // Should review the error, and fix the request
                    log.error("Should review the error, and fix the request", e);
                    log.info("HTTP Status: " + e.getStatus());
                    log.info("Error Code: " + e.getErrorCode());
                    log.info("Error Message: " + e.getErrorMessage());
                    jpushLog.setStatuscode(e.getErrorCode() + "");
                    jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                }
                // 保存推送日志
                jpushLog.setEnginnerId(eIds[i]);
                jpushLog.setType(PushConfig.ONE_PUSH);
                jpushLog.setRegistrationId(users1.get(0).getRegistrationId());
                jpushLog.setState(PushConfig.ACCEPT_STATE);
                jpushLog.setNoticeId(Long.parseLong(ServiceNoticeId));
                jpushLog.setServiceNo(serviceNo);
                jpushLog.setTitle(PushConfig.ACCEPT_TITLE);
                jpushLog.setContent(content);
                jpushLog.setExtra(extra.toString());
                jpushLog.setPushTime(new Date());
                jpushLog.setCreateTime(new Date());
                jpushLogMapper.insertJpushLog(jpushLog);
            }

            // 验证数据库中是否存在，如果存在修改状态，如果不存在新增并推送
            ServiceDetails serviceDetailsOld = selectServiceDetails(serviceNo, eIds[i]);
            if (serviceDetailsOld != null) {
                ServiceDetails serviceDetails2 = new ServiceDetails();
                serviceDetails2.setDelFlag("0");
                //拒绝时更新状态
                if (serviceDetailsOld.getState() == 6L) {
                    serviceDetails2.setState(0L);
                }
                serviceDetails2.setServiceNo(serviceNo);
                serviceDetails2.setFseId(eIds[i]);
                serviceDetails2.setTeamleaderId(assignId);
                serviceDetails2.setSendTime(new Date());
                serviceDetailsMapper.updateDelServiceDetails(serviceDetails2);

                PlanDetails planDetails2 = new PlanDetails();
                planDetails2.setDelFlag("0");
                //拒绝时更新状态
                if (serviceDetailsOld.getState() == 6L) {
                    planDetails2.setState("0");
                    planDetails2.setIsAccept("2");
                }

                planDetails2.setServiceNo(serviceNo);
                planDetails2.setFseId(eIds[i]);
                planDetailsMapper.updateDelPlanDetail(planDetails2);
                continue;
            }

            PlanDetails planDetails = new PlanDetails();
            planDetails.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
            planDetails.setServiceNo(serviceNo);
            planDetails.setFseId(eIds[i]);
            planDetails.setFseName(eNames[i]);
            planDetails.setIsAccept("2");
            planDetails.setState("0");
            planDetails.setDelFlag("0");
            planDetails.setCreateTime(new Date());
            planDetailsMapper.insertStPlanDetails(planDetails);

            ServiceDetails serviceDetails = new ServiceDetails();
            serviceDetails.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
            serviceDetails.setServiceNo(serviceNo);
            serviceDetails.setFseId(eIds[i]);
            serviceDetails.setFseName(eNames[i]);
            serviceDetails.setState(0L);
            serviceDetails.setDelFlag("0");
            serviceDetails.setCreateTime(new Date());
            serviceDetails.setUpdateBy(planDetails.getId() + "");
            serviceDetails.setTeamleaderId(assignId);
            serviceDetails.setSendTime(new Date());
            serviceDetailsMapper.insertServiceDetails(serviceDetails);
        }
        // cc 通知开始
        //查询 cc
        ServiceDetails serviceDetailsSearch = new ServiceDetails();
        serviceDetailsSearch.setServiceNoticeId(Long.parseLong(ServiceNoticeId));
        serviceDetailsSearch.setDelFlag("0");
        List<ServiceDetails> detailsListSearch = serviceDetailsMapper.selectServiceDetailsList(serviceDetailsSearch);
        StringBuffer enids = new StringBuffer();

        if (detailsListSearch.size() > 0) {
            serviceNo = detailsListSearch.get(0).getServiceNo();
            for (ServiceDetails details : detailsListSearch) {
                if (!"6".equals(details.getState() + "")) {
                    enids.append(details.getFseId() + ",");
                }
            }

            String dnginnerIds = enids.toString();
            if (dnginnerIds.length() > 1) {
                String ids = dnginnerIds.substring(0, dnginnerIds.length() - 1);
                String ccFlag = ccService.dispatchServicehandle(assignId, new Date(), serviceNo, ids);
                if (!"1".equals(ccFlag)) {
                    return new ResponseWithData<>().success().msg("CC接口调用异常").code(200);
                }
            }

        }
//        sdsd
//        String enids = EnginnerIds.substring(0, EnginnerIds.length() - 1);
//        String ccFlag= ccService.dispatchServicehandle(assignId,new Date(), serviceNo, enids);
//        if(!"1".equals(ccFlag)){
//            return new ResponseWithData<>().success().msg("CC接口调用异常").code(200);
//        }
        //cc 通知结束

        return new ResponseWithData<>().success().msg("派单成功").code(200);
    }

    @Override
    public ResponseWithData<?> AssociatedCustomers(String ServiceNoticeId, String EnginnerId, String signInTime, String signIn, String fillInLog, String state, String planId) throws Exception {
//        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
//        List<PlanDetails> list = planDetailsMapper.AssociatedCustomers(EnginnerId, serviceNotice.getCustomerName(), signInTime, signIn, fillInLog, state, planId);
//        List<PlanDetails> listResult = new ArrayList<PlanDetails>();
//        for (PlanDetails planDetails : list) {
//            if (StringUtils.isEmpty(planDetails.getHopeBusinessHours())) {
//                planDetails.setHopeBusinessHours("");
//            }
//            //排除上一次已签离但未填写日志的 上面计划
//            PlanDetails detailSearch= new  PlanDetails();
//            detailSearch.setServiceNo(planDetails.getServiceNo());
//            detailSearch.setFseId(planDetails.getFseId());
//            List<PlanDetails> planDetailsListSearch=planDetailsMapper.selectStPlanDetailsList(detailSearch);
//            // 判断该通知 上次已经填写过日志，可以添加日志。
//            if(planDetailsListSearch.size()>1){
//                PlanDetails temp=planDetailsListSearch.get(1);
//                if(temp!=null){
//                    if("1".equals(temp.getFillInLog())){
//                        listResult.add(planDetails);
//                    }
//                }
//            }else{
//                //
//                listResult.add(planDetails);
//            }
//
//
//        }
//        return new ResponseWithData<>().success(listResult).msg("查询成功").code(200);

        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
        List<PlanDetails> list = planDetailsMapper.AssociatedCustomers(EnginnerId, serviceNotice.getCustomerName(), signInTime, signIn, fillInLog, state, planId);
        List<PlanDetails> listResult = new ArrayList<PlanDetails>();
        for (PlanDetails planDetails : list) {
            ServiceNotice serviceNoticeTemp = serviceNoticeMapper.selectServiceNoticeById(planDetails.getServiceNoticeId());
            if (serviceNoticeTemp.getAppState() != 3) {
                if (StringUtils.isEmpty(planDetails.getHopeBusinessHours())) {
                    planDetails.setHopeBusinessHours("");
                }
                //排除上一次已签离但未填写日志的 上面计划
                PlanDetails detailSearch = new PlanDetails();
                detailSearch.setServiceNo(planDetails.getServiceNo());
                detailSearch.setFseId(planDetails.getFseId());
                List<PlanDetails> planDetailsListSearch = planDetailsMapper.selectStPlanDetailsList(detailSearch);
                // 判断该通知 上次已经填写过日志，可以添加日志。
                if (planDetailsListSearch.size() > 1) {
                    PlanDetails temp = planDetailsListSearch.get(1);
                    if (temp != null) {
                        if ("1".equals(temp.getFillInLog())) {
                            ServiceDetails tempDetail = new ServiceDetails();
                            tempDetail.setFseId(planDetails.getFseId());
                            tempDetail.setServiceNo(planDetails.getServiceNo());
                            List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(tempDetail);
                            ServiceDetails details = serviceDetailsList.get(0);
                            if (4 != details.getState()) {
                                listResult.add(planDetails);
                            }
                        }
                    }
                } else {
                    ServiceDetails tempDetail = new ServiceDetails();
                    tempDetail.setFseId(planDetails.getFseId());
                    tempDetail.setServiceNo(planDetails.getServiceNo());
                    List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(tempDetail);
                    ServiceDetails details = serviceDetailsList.get(0);
                    if (4 != details.getState()) {
                        listResult.add(planDetails);
                    }

                }

            }
        }
        return new ResponseWithData<>().success(listResult).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> AssociatedCustomersByBatch(String ServiceNoticeId, String EnginnerId, String signInTime, String signIn, String fillInLog, String state, String planId) throws Exception {
//        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
//        BatchLog batchlog= new BatchLog();
//        batchlog.setServiceNo(serviceNotice.getServiceNo());
//        batchlog.setEnginnerId(new Long(EnginnerId));
//        batchlog.setPlanId(new Long(planId));
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        batchlog.setCreateTime(formatter.parse(signInTime));
//
//        List<BatchLog> batchLogList= batchLogMapper.selectBatchLogList(batchlog);
//        String rel_service_no="";
//        String rel_plan_id="";
//        for(BatchLog batchLog:batchLogList){
//            if(batchLog.getRelServiceNo()!=null){
//                rel_plan_id=batchLog.getRelPlanId()+"";
//                rel_service_no=batchLog.getRelServiceNo();
//                break;
//            }
//
//        }
//        List<PlanDetails> PlanDetailslist =new ArrayList<>();
//        if(!"".equals(rel_service_no)&&!"".equals(rel_plan_id)){
//            //List<PlanDetails> list = planDetailsMapper.AssociatedCustomersByBatch(EnginnerId, rel_service_no, serviceNotice.getCustomerName(), signInTime, signIn, fillInLog, state, planId);
//            List<PlanDetails> list = planDetailsMapper.AssociatedCustomers(EnginnerId, serviceNotice.getCustomerName(), signInTime, signIn, fillInLog, state, null);
//            for (PlanDetails planDetails : list) {
//             if (StringUtils.isEmpty(planDetails.getHopeBusinessHours())) {
//                    planDetails.setHopeBusinessHours("");
//            }
//             if(!"4".equals(planDetails.getState())){
//                 PlanDetailslist.add(planDetails);
//             }
//
//            }
//            return new ResponseWithData<>().success(PlanDetailslist).msg("查询成功").code(200);
//        }
//
//        return new ResponseWithData<>().msg("不存在关联服务").code(200);
        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
        List<PlanDetails> planDetailslist = new ArrayList<>();
        List<PlanDetails> list = planDetailsMapper.AssociatedCustomers(EnginnerId, serviceNotice.getCustomerName(), signInTime, signIn, fillInLog, state, null);
        if (list.size() > 0) {
            for (PlanDetails planDetails : list) {
                if (StringUtils.isEmpty(planDetails.getHopeBusinessHours())) {
                    planDetails.setHopeBusinessHours("");
                }
                planDetailslist.add(planDetails);

            }
        }
        if (planDetailslist.size() > 0) {
            return new ResponseWithData<>().success(planDetailslist).msg("查询成功").code(200);
        }

        return new ResponseWithData<>().msg("不存在关联服务").code(200);
    }



    @Override
    public ResponseWithData<?> associatedCustomersByReport(String ServiceNoticeId, String EnginnerId, String signInTime,  String state) throws Exception {

        List<Map<String, String>> offLineDatas = new ArrayList<>();
        Map<String, String> offLineData = new HashMap<>();
        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
        List<PlanDetails> planDetailslist =new ArrayList<>();
        List<PlanDetails> list = planDetailsMapper.AssociatedCustomers(EnginnerId, serviceNotice.getCustomerName(), signInTime, null, null, state, null);
        if(list.size()>0){
            for (PlanDetails planDetails : list) {
                ReportInfo stReportInfo =new ReportInfo();
                stReportInfo.setRelServiceNo(new Long(1));
                stReportInfo.setSyncFlag("1");
                stReportInfo.setServiceResult("1");
                stReportInfo.setPlanId(planDetails.getId());
                stReportInfo.setServiceNo(planDetails.getServiceNo());
                stReportInfo.setEnginnerId(new Long(planDetails.getFseId()));
                List<ReportInfo> reportInfoList = reportInfoMapper.selectStReportInfoList(stReportInfo);
                if(reportInfoList.size()==0){
                    offLineData.put("finished","1");
                    offLineDatas.add(offLineData);
                    return new ResponseWithData<>().success(offLineDatas).msg("查询成功").code(200);

                }

            }
        }

        offLineData.put("finished","0");
        offLineDatas.add(offLineData);
        return new ResponseWithData<>().success(offLineDatas).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> AssociatedCustomersByMySelf(String ServiceNoticeId, String EnginnerId, String signInTime, String signIn, String fillInLog, String state, String planId) throws Exception {

        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(Long.parseLong(ServiceNoticeId));
        List<PlanDetails> list = planDetailsMapper.AssociatedCustomers(EnginnerId, serviceNotice.getCustomerName(), signInTime, signIn, fillInLog, state, planId);
        for (PlanDetails planDetails : list) {
            if (StringUtils.isEmpty(planDetails.getHopeBusinessHours())) {
                planDetails.setHopeBusinessHours("");
            }
        }
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }


    @Override
    public ResponseWithData<?> getServiceNoticeList(String EnginnerId, Long state, String ServiceNoticeId, String customerName, String serviceType, String instrumentSerialNumber) throws Exception {

        List<ServiceNotice> list = serviceNoticeMapper.getServiceNoticeList(EnginnerId, null==state?null:state.toString(), ServiceNoticeId, customerName, serviceType, instrumentSerialNumber,null,null,null);
        for (ServiceNotice serviceNotice1 : list) {
            if (StringUtils.equals("1", serviceNotice1.getUserIsdpel())) {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getEnginnerType());
                }
            } else {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType(serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType(serviceNotice1.getEnginnerType());
                }
            }

            StInfoUpdate stInfoUpdate = new StInfoUpdate();
            stInfoUpdate.setServiceNo(serviceNotice1.getServiceNo());
            stInfoUpdate.setDelFlag("0");
            stInfoUpdate.setType("1");
            //stInfoUpdate.setStatus(0L);
            List<StInfoUpdate> stInfoUpdateList = stInfoUpdateMapper.selectStInfoUpdateList(stInfoUpdate);
            //1 表示不一致，0 表示一致
            if (stInfoUpdateList.size() > 0) {
                serviceNotice1.setSnflag("1");
            } else {
                serviceNotice1.setSnflag("0");
            }
            ServiceInstrument serviceInstrument= serviceInstrumentMapper.selectServiceInstrumentByServiceNoticeId(serviceNotice1.getId());
            serviceNotice1.setInstrumentNo(serviceInstrument.getInstrumentNo());
            serviceNotice1.setInstrumentSerialNumber(serviceInstrument.getInstrumentSerialNumber());
        }
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

    @Override
    public ResponseWithData<?> getClosedNoticeList(String EnginnerId, Long AppState, String serviceNo, String customerName, String serviceType, String instrumentSerialNumber) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date endDate = new Date();
        Date startDate = DateUtils.addDays(endDate, -30);
        String sDate = formatter.format(startDate) + " 00:00:00";
        String eDate = formatter.format(endDate) + " 23:59:59";
        List<ServiceNotice> list = serviceNoticeMapper.getClosedNoticeList(EnginnerId, AppState, serviceNo, sDate, eDate, customerName, serviceType, instrumentSerialNumber);
        return new ResponseWithData<>().success(list).msg("查询成功").code(200);
    }

    @Override
    public List<ServiceNotice> getTeamServiceNotice(ServiceNotice serviceNotice) {
        return serviceNoticeMapper.getTeamServiceNotice(serviceNotice);
    }

    @Override
    public Integer getTeamServiceNoticeCount(ServiceNotice serviceNotice) {
        return CollectionUtils.size(getTeamServiceNotice(serviceNotice));
    }

    @Override
    public List<ServiceNotice> getFseReportNotice(ServiceNotice serviceNotice) {
        //过滤没有报告的
        List<ServiceNotice> serviceNoticeList =  serviceNoticeMapper.getFseReportNoticeFourType(serviceNotice);
        return serviceNoticeList;
    }

    @Override
    public List<ServiceNotice> getFseReportNoticeAll(ServiceNotice serviceNotice) {
        //维护工作报告查询所有
        List<ServiceNotice> serviceNoticeList =  serviceNoticeMapper.getFseReportNoticeFourTypeAll(serviceNotice);
        return serviceNoticeList;
    }
    @Override
    public List<ServiceNotice> getFseReportNoticeSubmitByErrorOrHot(ServiceNotice serviceNotice) {
        //过滤只有ERROR  或 hot报告的
        List<ServiceNotice> serviceNoticeList =  serviceNoticeMapper.getFseReportNoticeSubmitByErrorOrHot(serviceNotice);
        return serviceNoticeList;
    }

    @Override
    public ResponseWithData closeServiceNotice(String serviceNo, String closePersonId) throws Exception {
        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeByServiceNo(serviceNo);
        if (null == serviceNotice) {
            return new ResponseWithData().error("服务单不存在").code(201);
        }
        serviceNotice.setAppIsAccept("1");
        serviceNotice.setCcClosePersonId(closePersonId);
        serviceNotice.setAppState(3L);
        if(ObjectUtils.isEmpty(serviceNotice.getUpdateDate())){
            serviceNotice.setUpdateDate(new Date());
        }
        serviceNoticeMapper.updateServiceNotice(serviceNotice);
        return new ResponseWithData<>().success().msg("关闭服务通知成功").code(200);
    }

    private String getStartWorkingTime(List<ServiceLog> serviceLogs) {
        ServiceLog minStartTime = Collections.min(serviceLogs, new Comparator<ServiceLog>() {
            @Override
            public int compare(ServiceLog o1, ServiceLog o2) {
                int flag = 0;
                try {
                    if (null != o1.getStartTime() && null != o2.getStartTime()) {
                        if (o1.getStartTime().getTime() > o2.getStartTime().getTime()) {
                            flag = 1;
                        } else if (o1.getStartTime().getTime() < o2.getStartTime().getTime()) {
                            flag = -1;
                        } else {
                            flag = 0;
                        }
                    } else {
                        if (null == o2.getStartTime() && null != o1.getStartTime()) {
                            flag = -1;
                        } else if (null == o1.getStartTime() && null != o2.getStartTime()) {
                            flag = 1;
                        } else {
                            flag = 0;
                        }
                    }
                } catch (Exception e) {
                    log.error("程序异常", e.getMessage());
                }
                return flag;
            }
        });
        if (null != minStartTime) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(minStartTime.getStartTime());
        }
        return "";
    }

    private String getEndWorkingTime(List<ServiceLog> serviceLogs) {
        ServiceLog maxEndTime = Collections.max(serviceLogs, new Comparator<ServiceLog>() {
            @Override
            public int compare(ServiceLog o1, ServiceLog o2) {
                int flag = 0;
                try {
                    if (null != o1.getEndTime() && null != o2.getEndTime()) {
                        if (o1.getEndTime().getTime() > o2.getEndTime().getTime()) {
                            flag = 1;
                        } else if (o1.getEndTime().getTime() < o2.getEndTime().getTime()) {
                            flag = -1;
                        } else {
                            flag = 0;
                        }
                    } else {
                        if (null == o2.getEndTime() && null != o1.getEndTime()) {
                            flag = -1;
                        } else if (null == o1.getEndTime() && null != o2.getEndTime()) {
                            flag = 1;
                        } else {
                            flag = 0;
                        }
                    }
                } catch (Exception e) {
                    log.error("程序异常, {}", e.getMessage());
                }
                return flag;
            }
        });
        if (null != maxEndTime) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(maxEndTime.getEndTime());
        }
        return "";
    }

    @Override
    public ResponseWithData getServiceNoticeDetailsAndReportCount(String serviceNo, Long serviceNoticeId, Long planId, Long enginnerId) {
        Map<String, Object> resultMap = new HashMap<>();
        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(serviceNoticeId);
        if (null == serviceNotice) {
            return new ResponseWithData().error("服务单不存在").code(201);
        }
        resultMap.put("serviceNotice", serviceNotice);

        PlanDetails planDetails = planDetailsMapper.selectStPlanDetailsById(planId);
        resultMap.put("planDetails", planDetails);

        ServiceInstrument serviceInstrument = serviceInstrumentMapper.selectServiceInstrumentByServiceNoticeId(serviceNotice.getId());
        // cc  接口验证功能
        String response = ccService.getParamTables1("MDList", enginnerId);
        if (response == null) {
            return null;
        }
        List<Map<String, String>> results = new ArrayList<>();
        try {
            JSONObject jsonObject = JSONObject.parseObject(response);
            if ("1".equals(jsonObject.get("status"))) {
                JSONArray array = jsonObject.getJSONArray("record");
                if (null != array) {
                    for (int i = 0; i < array.size(); i++) {
                        Map<String, String> result = new HashMap<>();
                        result.put("RegisterNo", array.getJSONObject(i).getString("RegisterNo"));
                        results.add(result);
                    }
                }
            }
        } catch (Exception e) {
            return null;
        }
        if(results.size()>0){
            for(int i=0;i<results.size();i++){
                Map<String, String> stringMap= results.get(i);
                String no= stringMap.get("RegisterNo").toString();
                if(no.equals(serviceInstrument.getSapMaterialNo())){
                    serviceInstrument.setMdsign("1");
                    break;
                }else{
                    serviceInstrument.setMdsign("0");
                }
            }
        }else{
            serviceInstrument.setMdsign("0");
        }

        resultMap.put("serviceInstrument", serviceInstrument);
        InstrumentInfo instrumentInfo = instrumentInfoMapper.selectInstrumentInfoByServiceNo(serviceNotice.getServiceNo());
        resultMap.put("instrumentInfo", instrumentInfo);


        // 查询已完成并且已提交的电话解决报告或现场服务报告
        List<ReportInfo> reportInfos = reportInfoMapper.selectReportFinishByServiceNo(serviceNo);
        if (!ObjectUtils.isEmpty(reportInfos)) {
            for (ReportInfo reportInfo : reportInfos) {
                Map<String, String> map = new HashMap();
                ReportInfo reportInfoItem = new ReportInfo();
                reportInfoItem.setServiceNo(serviceNo);
                reportInfoItem.setEnginnerId(enginnerId);
                Map<String, Object> log = new HashMap();
                log.put("serviceNo", serviceNo);
                List<ServiceLog> serviceLogs = serviceLogMapper.selectTimeLog(log);
                if(!ObjectUtils.isEmpty(serviceLogs)){
                    String startWorkingTime = getStartWorkingTime(serviceLogs);
                    String endWorkingTime = getEndWorkingTime(serviceLogs);
                    map.put("startWorkingTime", startWorkingTime);
                    map.put("endWorkingTime", endWorkingTime);
                }
                reportInfo.setReportInfo(map);
            }
        }

        if (StringUtils.isNotEmpty(reportInfos)) {
            //reportInfos.addAll(reportInfos);
            resultMap.put("reportInfoFinishs", reportInfos);
        } else {
            resultMap.put("reportInfoFinishs", new ArrayList<>());
        }

        // 验收报告
        int acceptanceCount = reportInfoMapper.selectReportCountByServiceNoAndRelServiceNo(serviceNo, "4");
        resultMap.put("acceptanceCount", acceptanceCount);
        // 安装质量报告
        int installationquality = reportInfoMapper.selectReportCountByServiceNoAndRelServiceNo(serviceNo, "5");
        resultMap.put("installationquality", installationquality);

        // 查询关联日志
        List<ServiceLog> serviceLogs = serviceLogMapper.selectServiceLogsList(serviceNo, enginnerId);
        if (StringUtils.isNotEmpty(serviceLogs)) {
            resultMap.put("serviceLogs", serviceLogs);
        } else {
            resultMap.put("serviceLogs", new ArrayList<>());
        }
//从安装质量报告里面取一下

        return new ResponseWithData().success(resultMap).code(200).msg("查询成功");
    }

    @Override
    public ResponseWithData getCCServiceNoticeList(Long enginnerId,String serviceNo,String custName,String instrumentSerialNumber,String startTime,String endTime) {
        List<ServiceNotice> datas = serviceNoticeMapper.getccServiceNoticeList(enginnerId.toString(),null,null,custName,null,instrumentSerialNumber,startTime,endTime,serviceNo);
        if (StringUtils.isEmpty(datas)) {
            datas = new ArrayList<>();
        }
        return new ResponseWithData().success(datas).code(200).msg("查询成功");
    }

    @Override
    public ResponseWithData<?> getAssignServiceNotice(String enginnerId, String state, String customerName, String serviceType, String instrumentSerialNumber) throws Exception {
        List<ServiceNotice> assignServiceNotice = serviceNoticeMapper.getAssignServiceNotice(enginnerId, state, customerName, serviceType, instrumentSerialNumber);

        for (ServiceNotice serviceNotice1 : assignServiceNotice) {

            if (StringUtils.equals("1", serviceNotice1.getUserIsdpel())) {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getEnginnerType());
                }
            } else {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType(serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType(serviceNotice1.getEnginnerType());
                }
            }
            ServiceInstrument serviceInstrument= serviceInstrumentMapper.selectServiceInstrumentByServiceNoticeId(serviceNotice1.getId());
            serviceNotice1.setInstrumentNo(serviceInstrument.getInstrumentNo());
            serviceNotice1.setInstrumentSerialNumber(serviceInstrument.getInstrumentSerialNumber());
        }
        return new ResponseWithData<>().success(assignServiceNotice).msg("查询成功").code(200);
    }

    @Override
    public List<ServiceNotice> getTeamServiceNotices(ServiceNotice serviceNotice) {

        List<ServiceNotice> list = serviceNoticeMapper.getTeamServiceNotices(serviceNotice);
        for (ServiceNotice serviceNotice1 : list) {
            if (StringUtils.equals("1", serviceNotice1.getUserIsdpel())) {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getEnginnerType());
                }
            } else {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType(serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType(serviceNotice1.getEnginnerType());
                }
            }
        }
        return list;
    }


    @Override
    public List<ServiceNotice> getTeamServiceNoticesBytl(ServiceNotice serviceNotice) {

        StringBuffer fseids= new StringBuffer();
        String fse="";
        if(serviceNotice.getTeamleaderId()!=null){
            User userSearch=new User();
            userSearch.setTeamleaderId(serviceNotice.getTeamleaderId());
            List<User> userList=userMapper.selectUserList(userSearch);
            fseids.append("'"+serviceNotice.getTeamleaderId()+"',");
            if(userList.size()>0){
                for( User user:userList){
                    fseids.append("'"+user.getEnginnerId()+"',");
                }

            }
            fse=fseids.toString().substring(0,fseids.toString().length()-1);
            serviceNotice.setTeamleaderId(fse);

        }
        List<ServiceNotice> list = serviceNoticeMapper.getTeamServiceNoticesBytl(serviceNotice);
        for (ServiceNotice serviceNotice1 : list) {
            if (StringUtils.equals("1", serviceNotice1.getUserIsdpel())) {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType("DPEL/" + serviceNotice1.getEnginnerType());
                }
            } else {
                if (StringUtils.isNotEmpty(serviceNotice1.getIsVip())) {
                    serviceNotice1.setEnginnerType(serviceNotice1.getIsVip());
                } else {
                    serviceNotice1.setEnginnerType(serviceNotice1.getEnginnerType());
                }
            }
        }
        return list;
    }

    @Override
    public Integer getTeamServiceNoticesCount(ServiceNotice serviceNotice){
        return serviceNoticeMapper.getTeamServiceNoticesCount(serviceNotice);
    }


    public List<Map<String, Object>> selectServiceNoticeListByNotLog(Map<String, Object> serviceNotice){
        List<Map<String, Object>> list = serviceNoticeMapper.selectServiceNoticeListByNotLog(serviceNotice);
        for(int i=0;i<list.size();i++){
            Map maptemp=list.get(i);
            String service_no= maptemp.get("service_no").toString();
            String id= maptemp.get("id").toString();

            ServiceDetails serviceDetails=new ServiceDetails();
            serviceDetails.setFseId(serviceNotice.get("enginnerId").toString());
            serviceDetails.setServiceNo(service_no);
            serviceDetails.setServiceNoticeId(new Long(id));
            List<ServiceDetails> serviceDetailsList= serviceDetailsMapper.selectServiceDetailsList(serviceDetails);
            if(serviceDetailsList.size()>0){
                ServiceDetails  serviceDetailsDto= serviceDetailsList.get(0);
                maptemp.put("plainId",serviceDetailsDto.getUpdateBy());
            }

        }
        return list;
    }
    public List<ReportInfo> getUnSubmitReport(String serviceNo){
        ReportInfo info = new ReportInfo();
        info.setServiceNo(serviceNo);
        //  info.setPlanId(reportInfo.getPlanId());
        info.setSyncFlag("0");
        //    info.setRelServiceNo(1L); //服务报告
        info.setDelFlag("0");
        List<ReportInfo> plist = reportInfoMapper.selectStReportInfoList(info);
        return plist;
    }

    @Override
    public Integer getAssignServiceNoticeCount(String enginnerId, String state) {
        List<ServiceNotice> assignServiceNotice = serviceNoticeMapper.getAssignServiceNotice(enginnerId, state, null, null, null);;
        return CollectionUtils.size(assignServiceNotice);
    }

    @Override
    public Integer getServiceNoticeListCount(String enginnerId, String state) {
        List<ServiceNotice> list = serviceNoticeMapper.getServiceNoticeList(enginnerId,  state , null, null, null, null,null,null,null);
        return CollectionUtils.size(list);
    }

    private ServiceDetails selectServiceDetails(String serviceNo, String fseId)
    {
        ServiceDetails serviceDetails = new ServiceDetails();
        serviceDetails.setServiceNo(serviceNo);
        serviceDetails.setFseId(fseId);
        List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(serviceDetails);
        if(serviceDetailsList!=null && serviceDetailsList.size()>0){
            return serviceDetailsList.get(0);
        }
        return null;
    }
    @Override
    public List<ServiceNotice> getAllCustomerSignListModify(Map map) {
        // TODO Auto-generated method stub
        return serviceNoticeMapper.getAllCustomerSignListModify(map);
    }
}